package org.droidpres.utils;

import android.util.Log;

import java.io.*;
//import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created with IntelliJ IDEA.
 * User: Nord
 * Date: 15.02.13
 * Time: 18:52
 */
public class Decompress {

    private String _zipFile;
    private String _location;

    public Decompress(String zipFile, String location) {
        _zipFile = zipFile;
        _location = location;
        _dirChecker("");
    }

    public boolean unzip() {
        ////ArrayList<String> listunzipped = new ArrayList<String>();
        boolean result = false;
        try{
            FileInputStream fin = new FileInputStream(_zipFile);
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                Log.v("Decompress", "********************************************************");
                Log.v("Decompress", "Unzipping " + ze.getName());
                //InputStream in = zip.getInputStream(entry);

                //ze.get

                if(ze.isDirectory()) {
                    _dirChecker(ze.getName());
                } else {
                    FileOutputStream fout = new FileOutputStream(_location + ze.getName());
                    ////listunzipped.add(_location + ze.getName());

                    byte[] buffer = new byte[4048];
                    int len;
                    while ((len = zin.read(buffer)) >= 0)
                        fout.write(buffer, 0, len);

                    //for (int c = zin.read(); c != -1; c = zin.read()) {
                    //    fout.write(c);
                    //}
                    zin.closeEntry();
                    fout.close();

                    //InputStream fread = new FileInputStream(_location + ze.getName());

                    /*
                    csv.Reader reader = new csv.Reader(new FileReader(_location + ze.getName()))
                            .delimiter(';').ignoreComments(true).ignoreEmptyLines(true).preserveSpaces(true);

                    List<String> result;// = new ArrayList<String>();
                    while( (result = reader.readLine()) != null ){
                        //Log.v("UnZip",""+result);
                    }  */

                }
            }
            zin.close();
            result = true;
        } catch(Exception e) {
            Log.e("Decompress", "unzip", e);
        }
        return result;
    }

    private void _dirChecker(String dir) {
        File f = new File(_location + dir);
        if(!f.isDirectory()) {
            f.mkdirs();
        }
    }

}
